package com.ze.familydayverlenovo;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;


import com.umeng.analytics.MobclickAgent;
import com.ze.commontool.LoadImageMgr;
import com.ze.commontool.NetHelper;
import com.ze.commontool.NotificationTools;
import com.ze.commontool.PublicInfo;
import com.ze.commontool.StringTools;
import com.ze.familydayverlenovo.R;
import com.ze.familydayverlenovo.adapter.DialogDetailListViewAdapter;
import com.ze.familydayverlenovo.adapter.DialogListViewAdapter;
import com.ze.familydayverlenovo.adapter.FamilyListViewAdapter;
import com.ze.familydayverlenovo.userinfo.UserInfoManager;
import com.ze.model.ModelDataMgr;
import com.ze.model.PhotoModel.PicInfo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DialogDetailActivity extends Activity {
	private List<Map<String, Object>> 	mList;
	private ListView										mListView;
	private View											mBtnBack;
	private BaseAdapter								mAdapter;
	private TextView									mTopName;
	
	private String 										mMsgToName;
	private String 										mMsgToPic;
	private String 										mMsgToPicVip;
	private String 										mSelfPic;
	private String 										mSelfPicVip;
	public String 											mMsgToUid;
	private EditText										mEtSay;
	private ProgressDialog							mProgressDialog;
	private Button 										mBtnSend;
	
	private View 										mBtnMore;
	private View 										mBtnPic;
	private View 										mTvPic;
	private View 										mBtnPhoto;
	private View 										mTvPhoto;
	private View 										mBtnCard;
	private View 										mTvCard;
	private View  										mLayoutMore;
	
	private int 												listViewLastItem;
	private View											mHeadView;
	public static boolean 							inDetailView = false;
	public static DialogDetailActivity			DialogDetailInstance = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dialog_detail);
		DialogDetailInstance = this;
		mMsgToName 		= getIntent().getStringExtra(DialogListViewAdapter.flag[1]);
		mMsgToUid  			= getIntent().getStringExtra(DialogListViewAdapter.flag[4]);
		mProgressDialog 	= new ProgressDialog(this);
		mProgressDialog.setCanceledOnTouchOutside(false);
		mProgressDialog.setMessage(getResources().getString(R.string.dialog_msg_load));

		mLayoutMore = findViewById(R.id.dialog_more_layout);
		
		mBtnMore 	= findViewById(R.id.dialog_detail_more);
		mBtnMore.setOnClickListener(buttonClickListener);
		mBtnPic 	= findViewById(R.id.dialog_detail_pic);
		mBtnPic.setOnClickListener(buttonClickListener);
		mTvPic		= findViewById(R.id.dialog_detail_pic_tv);
		mTvPic.setOnClickListener(buttonClickListener);
		
		mBtnPhoto 	= findViewById(R.id.dialog_detail_photo);
		mBtnPhoto.setOnClickListener(buttonClickListener);
		mTvPhoto		= findViewById(R.id.dialog_detail_photo_tv);
		mTvPhoto.setOnClickListener(buttonClickListener);
		
		mBtnCard 	= findViewById(R.id.dialog_detail_card);
		mBtnCard.setOnClickListener(buttonClickListener);
		mTvCard		= findViewById(R.id.dialog_detail_card_tv);
		mTvCard.setOnClickListener(buttonClickListener);
		
		
		
		mBtnBack = findViewById(R.id.dialog_detail_back);
		mBtnBack.setOnClickListener(buttonClickListener);
		mTopName = (TextView)findViewById(R.id.dialog_detail_object);
		mTopName.setText(mMsgToName);
		mHeadView = getLayoutInflater().inflate(R.layout.dialog_listview_head, null);
		mListView = (ListView)findViewById(R.id.dialog_detail_listview);
		mListView.setOnItemClickListener(itemClickListener);
		mList = new ArrayList<Map<String,Object>>();
		
		mAdapter = new DialogDetailListViewAdapter(this, mList);
		mListView.addHeaderView(mHeadView);
		mListView.setAdapter(mAdapter);
		mEtSay = (EditText)findViewById(R.id.dialog_detail_etSay);
		mEtSay.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if( hasFocus ){
					if( mLayoutMore.getVisibility() == View.VISIBLE )
					{
						mLayoutMore.setVisibility(View.GONE);
					}
				}
				
			}
		});
		mEtSay.setOnClickListener(buttonClickListener);
		loadTask();
		
		mBtnSend = (Button)findViewById(R.id.dialog_detail_send);
		mBtnSend.setOnClickListener(buttonClickListener);
		mSelfPicVip = UserInfoManager.getInstance(DialogDetailActivity.this).getItem("vip").getValue();
		mListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if ( firstVisible == 0 && scrollState == OnScrollListener.SCROLL_STATE_IDLE)
				{
					// 进行翻页操作+
				if(	 mListView.getHeaderViewsCount() == 0 )
				{
//					Toast.makeText(DialogDetailActivity.this, R.string.tips_msg_nodata, Toast.LENGTH_SHORT).show();
				}else
				{
					loadTask();
				}
							
				
//					Toast.makeText(DialogDetailActivity.this, "h", Toast.LENGTH_SHORT).show();
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				// 当listView中没有数据，或者数据超过100条，或者不是10的整数倍（即数据不足）时隐藏“更多”并取消onScroll事件的绑定
//				if (ma.getCount() % 10 > 0 || arrayAdapter.getCount() == 0)
//				{
//					listView.removeFooterView(listViewLoadingView);
//					listView.setOnScrollListener(null);
//				}
				firstVisible = firstVisibleItem;
				if( firstVisibleItem == 0 )
				{
//					Toast.makeText(DialogDetailActivity.this, "h", Toast.LENGTH_SHORT).show();
				}
//				if( mLayoutMore.getVisibility() == View.VISIBLE )
//				{
//					mLayoutMore.setVisibility(View.GONE);
//				}
			}
		});
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		inDetailView = false;
	}
	public boolean isEqualCurrentUid( String uid_a )
	{
		return mMsgToUid.equals(uid_a);
	}
	public void updateFromPushData(Bundle bundle)
	{
		String uidString = bundle.getString("uid");
		if (uidString.equals(mMsgToUid)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(DialogDetailListViewAdapter.flag[0], mMsgToPic);
			map.put(DialogDetailListViewAdapter.flag[1], unPackageContext( bundle.getString("msg")) );
			map.put(DialogDetailListViewAdapter.flag[2], System.currentTimeMillis()/1000 + "");
			map.put(DialogDetailListViewAdapter.flag[3], 0);
			map.put(DialogDetailListViewAdapter.flag[4], mMsgToPicVip);
			mList.add(map);
			mAdapter.notifyDataSetChanged();
//			final int notifyid = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
//			handler.postDelayed(new Runnable() {
//				
//				@Override
//				public void run() {
//					// TODO Auto-generated method stub
//					JPushInterface.clearNotificationById(DialogDetailActivity.this, notifyid);
//				}
//			}, 500);
			mListView.setSelection(mList.size()-1);
		}
	}
	Handler handler = new Handler();	
	@Override
	public void onResume() {
	    super.onResume();
	    inDetailView = true;
	    MobclickAgent.onResume(this);
	}
	@Override
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	public int firstVisible = -1;
	private static final int TYPE_TEXT 	= 0;
	private static final int TYPE_CARD 	= 1;
	private static final int TYPE_PIC  	= 2;
	private static final int TYPE_FEED 	= 3;
	private static final int TYPE_NOTICE = 4;
	
	
	public void sendMsgTask( int type , JSONObject object)
	{
		String tempString = "";
		if( type == TYPE_TEXT )
		{
			tempString = mEtSay.getText().toString().trim();
		}else if( type == TYPE_CARD ||  type == TYPE_PIC )
		{
			if( object != null )
			{
				tempString = packageContext( object.toString() ,type );
			}
		}
		final String msg = tempString;
		if (msg.length() < 1 ) {
			Toast.makeText(this, getResources().getString(R.string.tips_input_less0), Toast.LENGTH_SHORT).show();
			return;
		}
		new AsyncTask<String, String, String>()
		{
			Map<String, Object> map;
			protected void onPreExecute() {
//				mProgressDialog.show();
				InputMethodManager immInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
				immInputMethodManager.hideSoftInputFromWindow(DialogDetailActivity.this.getCurrentFocus().getWindowToken(), 0);
				
				 map = new HashMap<String, Object>();
				map.put(DialogDetailListViewAdapter.flag[0], mSelfPic);
				map.put(DialogDetailListViewAdapter.flag[1], unPackageContext(msg));
				map.put(DialogDetailListViewAdapter.flag[2],  "0");
				map.put(DialogDetailListViewAdapter.flag[3], 1);
				map.put(DialogDetailListViewAdapter.flag[4], mSelfPicVip);
				mList.add(map);
				mAdapter.notifyDataSetChanged();
				mEtSay.setText("");
				mListView.setSelection(mList.size()-1);
			};
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				String responString = null;
				try {
					responString = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_send_msg), 
							mMsgToUid, "",UserInfoManager.getInstance(DialogDetailActivity.this).getItem("m_auth").getValue(),
							URLEncoder.encode(msg, "utf-8"),"android");
				} catch (NotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return responString;
			}
			protected void onPostExecute(String result) {
//				if (mProgressDialog.isShowing()) {
//					mProgressDialog.hide();
//				}
				try {
					JSONObject object = new JSONObject(result);
					if (object.getInt("error") == 0) {
//						Map<String, Object> map = new HashMap<String, Object>();
//						map.put(DialogDetailListViewAdapter.flag[0], mSelfPic);
//						map.put(DialogDetailListViewAdapter.flag[1], msg);
//						map.put(DialogDetailListViewAdapter.flag[2], System.currentTimeMillis()/1000 + "");
//						map.put(DialogDetailListViewAdapter.flag[3], 1);
//						map.put(DialogDetailListViewAdapter.flag[4], mSelfPicVip);
//						
//						mList.add(map);
						if( map != null )
						{
							map.put(DialogDetailListViewAdapter.flag[2], System.currentTimeMillis()/1000 + "");
						}
						mAdapter.notifyDataSetChanged();
//						mEtSay.setText("");
//						mListView.setSelection(mList.size()-1);
					}else
					{
						if( map != null )
						{
							map.put(DialogDetailListViewAdapter.flag[2],  "-1");
						}
						mAdapter.notifyDataSetChanged();
						
						String errorMsg = object.getString("msg");
						if (errorMsg != null || !errorMsg.equals("")) {
							Toast.makeText(DialogDetailActivity.this,errorMsg, Toast.LENGTH_SHORT).show();
						}else
						{
							Toast.makeText(DialogDetailActivity.this, R.string.tips_msg_relax, Toast.LENGTH_SHORT).show();
						}
						
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.execute("");
	}
	boolean isLoading = false;
	
	public void loadTask()
	{
		if( isLoading)
		{
			Toast.makeText(DialogDetailActivity.this, R.string.tips_msg_has_run, Toast.LENGTH_SHORT).show();
			return;
		}
		new AsyncTask<String, String, String>(){
			
			protected void onPreExecute() {
				if( mList.size() == 0 )
				{
					
//					mProgressDialog.show();
				}else
				{
//					mListView.addHeaderView(mHeadView);
				}
				
				isLoading = true;
			};
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				String endtime = mList.size() != 0 ? (String)mList.get( 0 ).get(DialogDetailListViewAdapter.flag[2]) : "";
				String respon = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_dialog_detail), 
						UserInfoManager.getInstance(DialogDetailActivity.this).getItem("m_auth").getValue(),
						mMsgToUid,endtime);
				return respon;
			}
			protected void onPostExecute(String result) {
				if (mProgressDialog.isShowing()) {
					mProgressDialog.hide();
				}
				isLoading = false;
				
				try {
					JSONObject jsonObject = new JSONObject(result);
					if ( 0 == jsonObject.getInt("error") )
					{
						mMsgToPic 		= LoadImageMgr.getInstance().getMiddleHead( 
								jsonObject.getJSONObject("data").getJSONObject("touser").getString("avatar") );
						mMsgToPicVip 	= jsonObject.getJSONObject("data").getJSONObject("touser").getString("vipstatus") ;
						mSelfPic 				=  LoadImageMgr.getInstance().getMiddleHead( 
								jsonObject.getJSONObject("data").getJSONObject("fromuser").getString("avatar") );
						if(  ! jsonObject.getJSONObject("data").isNull("dialog") )
						{
							JSONArray array = jsonObject.getJSONObject("data").getJSONArray("dialog");
							int size = array.length();
							JSONObject temp;
							Map<String, Object> object;
							List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
							if( size < 5 )
							{
								mListView.removeHeaderView(mHeadView);
								Toast.makeText(DialogDetailActivity.this, R.string.tips_msg_finish_load, Toast.LENGTH_SHORT).show();
							}
							for (int i = 0; i < size; i++) {
								temp = array.getJSONObject(i);
								object = new HashMap<String, Object>();
								
								object.put(DialogDetailListViewAdapter.flag[1], unPackageContext( 
										temp.getString("message") ) );
								object.put(DialogDetailListViewAdapter.flag[2], temp.getString("dateline"));
								if (temp.getString("msgfromid").equals(mMsgToUid)) {
									object.put(DialogDetailListViewAdapter.flag[3], 0);
									object.put(DialogDetailListViewAdapter.flag[0], mMsgToPic);
									object.put(DialogDetailListViewAdapter.flag[4], mMsgToPicVip);
								}else
								{
									object.put(DialogDetailListViewAdapter.flag[3], 1);
									object.put(DialogDetailListViewAdapter.flag[0], mSelfPic);
									object.put(DialogDetailListViewAdapter.flag[4], mSelfPicVip);
								}
								dataList.add(object);
							}
							boolean isMore = mList.size() != 0 ;
							mList.addAll(0, dataList);
							mAdapter.notifyDataSetChanged();
							if ( !  isMore ) {
								mListView.setSelection(mList.size()-1);
							}else {
								mListView.setSelection(dataList.size()-1);
							}
						}else {
							mListView.removeHeaderView(mHeadView);
							Toast.makeText(DialogDetailActivity.this, R.string.tips_msg_finish_load, Toast.LENGTH_SHORT).show();
						}
					}else {
						mListView.removeHeaderView(mHeadView);
						Toast.makeText(DialogDetailActivity.this, R.string.error_net, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.execute("");
	}
	public static final String SPECIAL_STRING_TO = "__;F;__";
	public static final String SPECIAL_STRING_FROM = "\"";
	
	/**
	 * 从服务器替换特殊符号
	 * @param context
	 * @return
	 */
	
	public String unPackageContext(String context)
	{
		if(context.contains(SPECIAL_STRING_TO))
		{
			context = context.replace(SPECIAL_STRING_TO, SPECIAL_STRING_FROM);
		}
		return context;
	}
	/**
	 * 从客户端打包发送服务器
	 * @param context
	 * @return
	 */
	public String packageContext(String context, int type)
	{
		// since the fucking server cut the string in dialog list
		// {"query":"Pizza","locations":[94043,90210]}

		if( type == TYPE_CARD )
		{
			context = "{\"version\":\"1.6\",\"type\":\"card\"," + context.substring(1);
		}else  if( type == TYPE_PIC ) {
			context = "{\"version\":\"1.6\",\"type\":\"image\"," + context.substring(1);
		}
		if(context.contains(SPECIAL_STRING_FROM))
		{
			context = context.replace(SPECIAL_STRING_FROM,SPECIAL_STRING_TO);
		}
		return context;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if ( data == null )
		 {
			 if( requestCode != 2 )
			 {
//				 Toast.makeText(this, text, duration)
				 return;
			 }
		 }
	        switch (requestCode) {  
	        // 如果是直接从相册获取  
	        case 1:  
//	            startPhotoZoom(data.getData());  
	        	  if(data != null){  
	        		  ContentResolver resolver = getContentResolver();
	  				Uri originalUri = data.getData();
	  				if (originalUri != null) {
	  					try {
							 InputStream is = resolver.openInputStream(originalUri);
							 BitmapFactory.Options options = new BitmapFactory.Options();
							 options.inJustDecodeBounds = false;
							 options.inSampleSize = 1;  // width，hight设为原来的三分一
							 options.inPreferredConfig = Bitmap.Config.RGB_565;
							 options.inPurgeable = true;
							 options.inInputShareable = true;
							 Bitmap temp = BitmapFactory.decodeStream(is, null, options);
							//Bitmap temp = MediaStore.Images.Media.getBitmap(resolver,originalUri);
							 Bitmap bmp = Bitmap.createScaledBitmap(temp, 1024, 
									1024 * temp.getHeight() / temp.getWidth(), true);
							 temp.recycle();
							 System.gc();
							 uploadPic(bmp);  
	  					}catch (Exception e) {
							// TODO: handle exception
						}
	  				}
		            }  
	            break;  
	        // 如果是调用相机拍照时  
	        case 2:  
	        	if (resultCode == -1 ) {
	        		File temp = new File(ModelDataMgr.ROOT_PATH
		                    + ModelDataMgr.ICON_TEMP);  
		            if(temp.exists())
		            	uploadPic(Uri.fromFile(temp));  
				}
	            break;  
	        // 取得裁剪后的图片  
	        case 3:  
	            /**  
	             * 非空判断大家一定要验证，如果不验证的话，  
	             * 在剪裁之后如果发现不满意，要重新裁剪，丢弃  
	             * 当前功能时，会报NullException，小马只  
	             * 在这个地方加下，大家可以根据不同情况在合适的  
	             * 地方做判断处理类似情况  
	             *   
	             */ 
	            if(data != null){  
	                uploadPic(data);  
	            }  
	            File file = new File(ModelDataMgr.ROOT_PATH
	                    + ModelDataMgr.ICON_TEMP);  
	            if( file != null )
	            	file.delete();
	            break;  
	        default:  
	            break;  
	 
	        }  
		JSONObject object;
		try {
		
			if( requestCode == 0 )
			{
				// card: from MyfamilyMemberActivity
				object = new JSONObject();
//				object.put("version", "1.6");
//				object.put("type", "card");
				object.put("uid", data.getStringExtra("id"));
				object.put("avatar", data.getStringExtra("head"));
				object.put("name", data.getStringExtra("name"));
				object.put("username", data.getStringExtra("name"));	// 之前详情没存，暂与name一致
				object.put("vipstatus", data.getStringExtra("vip"));
				
				sendMsgTask(TYPE_CARD,object);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	public void uploadPic( Intent picdata )
	{
		 Bundle extras = picdata.getExtras();  
	        if (extras != null) {  
	            Bitmap photo = extras.getParcelable("data");  
	            final Drawable drawable = new BitmapDrawable(photo); 
	            uploadPic( drawable);
	        }
	}
	public void uploadPic( Uri picUri )
	{
		 ContentResolver cr = this.getContentResolver();  
			try {
				 Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(picUri)); 
				   final Drawable drawable = new BitmapDrawable(bitmap); 
				   uploadPic( drawable);
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
	}
	public void uploadPic( Bitmap bitmap )
	{
		if (bitmap != null) {  
            final Drawable drawable = new BitmapDrawable(bitmap); 
            uploadPic( drawable);
		}
	}
	public void uploadPic(final Drawable drawable)
	{
		new AsyncTask<String, Integer, String>()
		{
			protected void onPreExecute() {
				NotificationTools.sendNotification(DialogDetailActivity.this,R.drawable.icon_upload, "正在上传图片...", 
						System.currentTimeMillis(), 
						"上传图片",
						"正在努力上传...",
						false,10086);
			};
			
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				String urlString = String.format(getResources().getString(R.string.http_upload_pic));
				String responString = NetHelper.uploadPicWithArgs(urlString, drawable, "Filedata",
						new String[]{"ac","op","m_auth"},
						new String[]{"upload","uploadphoto",UserInfoManager.getInstance(DialogDetailActivity.this).getItem("m_auth").getValue()});
				
				return responString;
			}
			protected void onPostExecute(String result) {
				JSONObject object;
//				if (uploadDialog.isShowing()) {
//					uploadDialog.hide();
//				}
				try {
					object = new JSONObject(result);
					if (object.getInt("error") == 0 ) {
						NotificationTools.sendNotification(DialogDetailActivity.this,R.drawable.icon_upload_ok, 
								"上传成功", 
								System.currentTimeMillis(), 
								"上传图片",
								"上传成功",
								true,10086);
						
						NotificationTools.clearNotificationById(DialogDetailActivity.this, 10086);
						
						String url = object.getJSONObject("data").getString("pic");
						JSONObject sendMsgObject = new JSONObject();
//						sendMsgObject.put("version", "1.6");
//						sendMsgObject.put("type", "image");
						sendMsgObject.put("imgurl", url);
						sendMsgTask(TYPE_PIC, sendMsgObject);
						// 把drawable 命名为 url 存在pic_cache
						LoadImageMgr.getInstance().putImageToCache(drawable, url);  // 120x120
						if(url.contains("!120X120"))
						{
							LoadImageMgr.getInstance().putImageToCache(drawable, url.replace("!120X120", "") );
						}
						
					}else
					{
						Toast.makeText(DialogDetailActivity.this, getResources().getString(R.string.dialog_msg_check_mauth), Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			};
		}.execute("");
	}
	private OnClickListener buttonClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if ( v == mBtnBack ) {
				DialogDetailActivity.this.finish();
			}else if( v== mBtnSend)
			{
				sendMsgTask(TYPE_TEXT,null);
			}else if( v == mEtSay){
				if( mLayoutMore.getVisibility() == View.VISIBLE )
				{
					mLayoutMore.setVisibility(View.GONE);
				}
			}
			else if( v == mBtnMore )
			{
				if( mLayoutMore.getVisibility() == View.GONE )
				{
					mLayoutMore.setVisibility(View.VISIBLE);
					InputMethodManager immInputMethodManager = 
						(InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
					immInputMethodManager.hideSoftInputFromWindow
					(DialogDetailActivity.this.getCurrentFocus().getWindowToken(), 0);
				}else
				{
					mLayoutMore.setVisibility(View.GONE);
				}
			}else if( v == mBtnPic || v == mTvPic )
			{
				Intent intent = new Intent(Intent.ACTION_PICK, null); 
                intent.setDataAndType(  
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  
                        "image/*");  
                startActivityForResult(intent, 1);  
			}else if( v == mBtnPhoto || v == mTvPhoto )
			{
				Intent intent = new Intent(  
                        MediaStore.ACTION_IMAGE_CAPTURE);  
                //下面这句指定调用相机拍照后的照片存储的路径  
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri  
                        .fromFile(new File(ModelDataMgr.ROOT_PATH,  
                        		ModelDataMgr.ICON_TEMP)));  
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, );
                startActivityForResult(intent, 2);  
			}else if( v == mBtnCard || v == mTvCard )
			{
				Intent intent = new Intent();
				intent.putExtra("dialog", true);
				intent.setClass(DialogDetailActivity.this, MyFamilyMemberActivity.class);
				startActivityForResult(intent, 0);
			}
		}
	};
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			boolean isContainHeadView = false;
			int 	itemOnClickPos = arg2;
			if( mListView.getHeaderViewsCount() > 0 )
			{
				// 说明添加了加载更多的headview
				isContainHeadView = true;
				if( arg2 != 0 )
				{
					// 在有头部的情况下，选中的数据项要-1
					itemOnClickPos = itemOnClickPos - 1;
				}else {
					// arg2 = 0 
					// 说明点击的是头部
					return;
				}
			}
			if( itemOnClickPos <  mList.size()  ){
				String say = (String) mList.get(itemOnClickPos).get("say");
				try {
					JSONObject object = new JSONObject(say);
					
					if ( ! object.isNull("type") ) {
						String type = object.optString("type");
						if( type.equals("card") )
						{
							Intent intent = new Intent();
							intent.setClass(DialogDetailActivity.this, UserInfoActivity.class);
							intent.putExtra(FamilyListViewAdapter.flag[0],
									object.getString("avatar"));
							intent.putExtra(FamilyListViewAdapter.flag[1],
									object.getString("name"));
							intent.putExtra(FamilyListViewAdapter.flag[2],
									"");
							intent.putExtra(FamilyListViewAdapter.flag[3],
									object.getString("uid"));
							intent.putExtra(FamilyListViewAdapter.flag[4],
									"");
							intent.putExtra(FamilyListViewAdapter.flag[5],
									object.optString("vipstatus", ""));
							startActivity(intent);
						}else if( type.equals("image") )
						{
							String picStrings[] = null;
							picStrings = new String[1];
							try{
								picStrings[0] = LoadImageMgr.getInstance().clearTail2(object.getString("imgurl"));
							}catch (Exception e) {
								// TODO: handle exception
								e.printStackTrace();
							}
							Intent intent = new Intent();
							intent.setClass(DialogDetailActivity.this, BigPicActivity.class);
							intent.putExtra("urls", picStrings);
							intent.putExtra("imgPos", 0);
							startActivity(intent);
						}else {
							Intent intent = new Intent();        
							intent.setAction("android.intent.action.VIEW");    
							Uri content_url = Uri.parse("http://app.lenovo.com/");   
							intent.setData(content_url);  
							startActivity(intent);
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}
		
	};
}
